package com.glink.manage.common;

import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.io.IOUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : qiushaoshan
 * @create 2024/7/5 11:16
 */
public class ImagePreviewUtils {
    public ImagePreviewUtils() {
    }

    public static byte[] loadRawOrPreview(MultipartFile file) {
        return loadRawOrPreview(file, 0.2F, 0.05F);
    }

    public static byte[] smartZip(MultipartFile file, Integer maxWidth) {
        return smartZip(file, maxWidth, 0.5F);
    }

    public static byte[] smartZip(MultipartFile file, Integer maxWidth, Float quality) {
        try {
            BufferedImage image = ImageIO.read(file.getInputStream());
            if (image != null) {
                Integer w = image.getWidth();
                Float scale = maxWidth > w ? 1.0F : (float) maxWidth * 1.0F / (float) w;
                return loadRawOrPreview(file, scale, quality);
            } else {
                return null;
            }
        } catch (IOException var6) {
            return null;
        }
    }

    public static byte[] smartZip(MultipartFile file) {
        return smartZip(file, 48);
    }

    public static byte[] loadRawOrPreview(MultipartFile file, Float scale, Float quality) {
        InputStream inputStream = null;
        ByteArrayOutputStream dest = new ByteArrayOutputStream();

        try {
            inputStream = file.getInputStream();
            ImgZip(inputStream, dest, scale, quality);
            byte[] var5 = dest.toByteArray();
            return var5;
        } catch (Exception var9) {
            var9.printStackTrace();
        } finally {
            IOUtils.closeQuietly(dest);
            IOUtils.closeQuietly(inputStream);
        }

        return null;
    }

    public static void loadRawOrPreviewOptimizer(MultipartFile file, OutputStream dest, Float scale, Float quality) {
        InputStream inputStream = null;

        try {
            inputStream = file.getInputStream();
            ImgZip(inputStream, dest, scale, quality);
        } catch (Exception var9) {
            var9.printStackTrace();
        } finally {
            IOUtils.closeQuietly(inputStream);
        }

    }

    public static void loadRawOrPreviewOptimizer(MultipartFile file, OutputStream dest) {
        loadRawOrPreviewOptimizer(file, dest, 0.2F, 0.05F);
    }

    public static void ImgZip(InputStream source, OutputStream dest, Float scale, Float quality) {
        try {
            Thumbnails.of(new InputStream[]{source}).scale((double) scale).outputQuality(quality).toOutputStream(dest);
        } catch (IOException var5) {
            var5.printStackTrace();
        }

    }
}
